<template>
  <div >
    <a-menu
        theme="dark"
        :selectable="false"
        mode="horizontal"
        :style="{ lineHeight: '24px'}"
    >
      <a-menu-item>
        <a-icon type="appstore"/>
      </a-menu-item>
      <a-menu-item>
        <a-icon @click="makeScreenfull()" :type="fullscreen"/>
      </a-menu-item>
      <a-menu-item>
              <a-icon type="edit" @click="()=>{this.clipboardDrawer=true}" />
      </a-menu-item>
      <a-sub-menu>
              <span slot="title" class="submenu-title-wrapper"
              >
                <a-icon type="desktop"/></span>
        <a-menu-item-group title="Resolution">
          <a-menu-item @click="changeResolution([1920,1080])" key="setting:1">
            <a-icon type="fullscreen" /> 1920x1080
          </a-menu-item>
          <a-menu-item @click="changeResolution([1366,768])" key="setting:2">
            <a-icon type="fullscreen" /> 1360x768
          </a-menu-item>
          <a-menu-item @click="autoResize()" key="setting:3">
            <a-icon type="fullscreen" /> Auto Resize
          </a-menu-item>
          <a-menu-item key="setting:4">
            <a-icon type="fullscreen" /> Custom Resolution
          </a-menu-item>
        </a-menu-item-group>
      </a-sub-menu>
      <a-sub-menu>
              <span slot="title" class="submenu-title-wrapper"
              >
                <a-icon type="ellipsis"/></span>
        <a-menu-item-group title="Send Keys">
          <a-menu-item @click="sendCombinationKey(['65507', '65513', '65535'])" key="setting:1">
            <a-icon type="number" /> Ctrl+Alt+Delete
          </a-menu-item>
          <a-menu-item @click="sendCombinationKey(['65515', '114'])" key="setting:2">
            <a-icon type="number" /> WIN+R
          </a-menu-item>
          <a-menu-item key="setting:3">
            <a-icon type="number" /> Custom Keys
          </a-menu-item>
        </a-menu-item-group>
      </a-sub-menu>
      <a-sub-menu>
              <span slot="title" class="submenu-title-wrapper"
              >
                <a-icon type="setting" /></span>
        <a-menu-item-group title="Settings">
          <a-menu-item >
            waiting
          </a-menu-item>
        </a-menu-item-group>
      </a-sub-menu>
      <a-sub-menu>
              <span slot="title" class="submenu-title-wrapper"
              >
                <a-icon type="disconnect"/></span>
        <a-menu-item-group title="Disconnect">
          <a-menu-item key="setting:1">
            End Session
          </a-menu-item>
        </a-menu-item-group>
      </a-sub-menu>
    </a-menu>
    <a-drawer width="400"
              :visible="clipboardDrawer"
              placement="right"
              title="Clipboard"
              @close="()=>{this.clipboardDrawer=false;this.sendClipboard({'data':this.clipboardText,'type': 'text/plain'});this.sink.focus()}">
      <a-textarea v-model="clipboardText" :auto-size="{ minRows: 20, }"  />
    </a-drawer>
    <div id="display"/>
  </div>

</template>

<script>
import Guacamole from "guacamole-common-js";
import screenfull from 'screenfull'

export default {
  name: "Connect",
  data() {
    return {
      client: {},
      protocol: "",
      displayStyle: "",
      sessionId: "",
      fullscreen:"fullscreen",
      clipboardDrawer:false,
      clipboardText:"",
      sink:{}
    };
  },
  mounted() {
    this.protocol = this.$route.query.sessionProtocol;
    this.sessionId = this.$route.query.sessionId;
    document.querySelector('body').setAttribute('style', 'background-color:grey')
    this.initGuacamole();
  },
  methods: {
    makeScreenfull() {
      screenfull.toggle()
      this.fullscreen="fullscreen-exit"
    },
    initGuacamole() {
      this.$message.info('正在准备会话....');
      let tunnel = new Guacamole.WebSocketTunnel("/api/v1/ws/" + this.sessionId);
      //let tunnel = new Guacamole.WebSocketTunnel('ws://118.31.189.168/api/v1/ws/e026c02fbbf6f2610d11d2a48029f405?dpi=96&width=947&height=683&');
      let client = new Guacamole.Client(tunnel);
      let display = document.getElementById("display");
      display.appendChild(client.getDisplay().getElement());

      client.onerror = (error) =>{
        console.log(error.message);
        this.$message.error(error.message)
        this.$message.error("5秒后将关闭本页面")
        setTimeout(()=>{window.close()},5000)
      };

      this.$message.info('连接中....');
      let dpi =96;
      client.connect("dpi=" + dpi + "&width=" + window.innerWidth + "&height=" + (window.innerHeight - 25));

      this.$message.info('连接成功....');
      window.onunload = function () {
        client.disconnect();

      };

      //mouse
      let mouse = new Guacamole.Mouse(client.getDisplay().getElement());
      mouse.onmousedown = mouse.onmouseup = mouse.onmousemove = function (mouseState) {
          client.sendMouseState(mouseState);
      };

      client.getDisplay().showCursor(false);

      client.getDisplay().oncursor = (can, x, y) => {
        display.style.cursor = "url(" + can.toDataURL() + ") " + x + " " + y + " , auto";
      }

      let sink = new Guacamole.InputSink();
      display.appendChild(sink.getElement());
      sink.focus();

       //Keyboard
      let keyboard = new Guacamole.Keyboard(sink.getElement());
      keyboard.onkeydown = function (keysym) {
        client.sendKeyEvent(1, keysym);
      };
      keyboard.onkeyup = function (keysym) {
        client.sendKeyEvent(0, keysym);
      };
      this.client = client;
      this.sink=sink;

      if (this.protocol === 'ssh') {
        //client.getDisplay().d
        setTimeout(() => {
          this.autoResize()
        }, "1000");
      }

      //clipboard
      client.onclipboard=this.clientClipboardReceived;
      client.sendClipboard = this.sendClipboard;

      window.addEventListener('resize', this.autoResize);
    },
    sendCombinationKey(keys) {
      let that = this;
      for (let i = 0; i < keys.length; i++) {
        that.client.sendKeyEvent(1, keys[i]);
      }
      for (let j = 0; j < keys.length; j++) {
        that.client.sendKeyEvent(0, keys[j]);
      }
    },
    changeResolution(resolution) {
      this.client.sendSize(resolution[0], resolution[1])
    },
    autoResize() {
      this.client.sendSize(window.innerWidth, window.innerHeight - 25)
      this.fullscreen="fullscreen"
    },
    clientClipboardReceived(stream, mimetype)  {
      console.log('clientClipboardReceived', mimetype)
      let reader;
      // If the received data is text, read it as a simple string
      if (/^text\//.exec(mimetype)) {
        reader = new Guacamole.StringReader(stream);
        // Assemble received data into a single string
        let data = '';
        reader.ontext = function textReceived(text) {
          data += text;
        };
        // Set clipboard contents once stream is finished
        reader.onend = async () => {
          this.$copyText(data).then()
          this.clipboardText=data
        };

      }

      // Otherwise read the clipboard data as a Blob
      else {
        reader = new Guacamole.BlobReader(stream, mimetype);
        reader.onend = () => {
          this.clipboardText=reader.getBlob()
        }
      }
    },
    sendClipboard(data) {
      let writer;

      // Create stream with proper mimetype
      const stream = this.client.createClipboardStream(data.type);

      // Send data as a string if it is stored as a string
      if (typeof data.data === 'string') {
        writer = new Guacamole.StringWriter(stream);
        writer.sendText(data.data);
        writer.sendEnd();
      } else {

        // Write File/Blob asynchronously
        writer = new Guacamole.BlobWriter(stream);
        writer.oncomplete = function clipboardSent() {
          writer.sendEnd();
        };

        // Begin sending data
        writer.sendBlob(data.data);
      }

    }
  }
};
</script>

<style lang="less" scoped>

</style>